package com.example.librarymanagementsystembackend.advice;

import com.example.librarymanagementsystembackend.utils.ResponseData;
import com.example.librarymanagementsystembackend.utils.ResponseDataUtils;
import com.example.librarymanagementsystembackend.utils.TerminalFontColor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.time.LocalDateTime;

@ControllerAdvice
public class GlobalResponseWrapper implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    public static final String[] SWAGGER_PATHS = {
            "/swagger-ui.html",
            "/doc.html",
            "/webjars/**",
            "/v3/api-docs/**",
            "/swagger-resources/**",
            "/swagger-ui/**"
    };

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {

        Type actualReturnType = returnType.getGenericParameterType();
        return
//                !actualReturnType.equals(ResponseData.class) // 排除已经包装过的响应
//                !actualReturnType.equals(ResponseEntity.class); // 排除响应实体类型
                // ExceptionHandler返回的数据类型可能与Controller不一致，导致CAST异常，故需要被ResponseBodyAdvice处理
                !returnType.getExecutable().isAnnotationPresent(ExceptionHandler.class);
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 如果请求路径是 Swagger 相关路径，直接返回原始数据
        final String requestPath = request.getURI().getPath();
        for (String path : SWAGGER_PATHS) {
            if (antPathMatcher.match(path, requestPath)) {
                return body;
            }
        }

        // 打印日志
        String GREEN = TerminalFontColor.GREEN;
        String RESET = TerminalFontColor.RESET;
        System.out.println(
                GREEN + "[" + LocalDateTime.now() + "] " + RESET
                        + request.getMethod() + " " + request.getURI().getPath() + ":");

        if (body instanceof Resource) {
            System.out.println("(文件资源)");
            return body;
        }

        // 设置响应体数据类型（将可能出现的 String 返回类型对应的 text/plain 转为 application/json）
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 接口最终要返回的数据
        Object responseData = null;
        // 处理String类型返回值（String不能直接转ResponseData）
        if (body instanceof String) {
            try {
                responseData = objectMapper.writeValueAsString(ResponseDataUtils.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        // 已封装为ResponseData，直接返回
        if (body instanceof ResponseData) {
            responseData = body;
        }

        // 默认封装
        if (responseData == null)
            responseData = ResponseDataUtils.success(body);

        System.out.println(responseData);// 记录响应数据
        return responseData;
    }
}